<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2024/3/15
 * Time: 12:57
 */

namespace app\admin\controller;

use app\admin\model\Order as OrderModel;
use app\admin\traits\Crud;
use app\admin\validate\OrderValidate;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Request;
use think\Response;

class Order extends BaseAdminController
{
    private OrderModel $model;
    use Crud;

    public function initialize()
    {
        parent::initialize();
        $this->model         = new OrderModel();
        $this->validateClass = OrderValidate::class;
        $this->searchFields  = "id,name,user_id,no,create_time";
        $this->isEach        = 1;
    }

    public function format($list)
    {
        return $list->each(function ($item) {
            $item->amount    = $item->orderDetail()->sum('amount');
            $item->quantity  = $item->orderDetail()->sum('quantity');
            $item->real_name = $item->user()->value('name');//客户名称
        });
    }

    /**
     * 详情
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function detail(): Response
    {
        $param = Request::param();
        validate($this->validateClass)->scene('detail')->check($param);
        $sql   = $this->model;
        $sql   = $sql->withSearch($this->searchFields, $param);
        $order = $sql->order($this->orderSort)->field('id,no,user_id,remark')->find();
        if ($order) {
            $order->amount         = $order->orderDetail()->sum('amount');
            $order->quantity       = $order->orderDetail()->sum('quantity');
            $order->orderDetail    = $order->orderDetail()->select()->each(function ($item) {
                $item->goods_name = $item->goods()->field('id,name,no')->find();
                $item->goods_no   = $item->goodsRule()->field('id,spec_name')->find();
            })->visible(explode(',', 'id,img,quantity,amount,money'));
            $order->user           = $order->user()->field('id,name,real_name,mobile,address')->find();
            $order->user['remark'] = $order->remark;
        }
        return $this->success('获取成功', compact('order'));
    }
}